<template>
  <div class="post-detail-container">
    <!-- 主内容区域 -->
    <div class="main-content">
      <!-- 左侧贴吧信息 -->
      <div class="sidebar">
        <el-card class="bard-card">
          <div class="bard-cover">
            <el-image :src="bardInfo?.cover" fit="cover" class="cover-image"></el-image>
          </div>
          <div class="bard-info">
            <h3>{{ bardInfo?.bardName }}</h3>
            <el-button
                type="primary"
                :icon="Plus"
                :disabled="bardInfo?.isFollow"
                class="follow-btn"
            >
              {{ bardInfo?.isFollow ? '已关注' : '关注贴吧' }}
            </el-button>
            <div class="bard-stats">
              <div class="stat-item">
                <span class="stat-value">{{ bardInfo?.followerCount }}</span>
                <span class="stat-label">关注</span>
              </div>
              <div class="stat-item">
                <span class="stat-value">{{ bardInfo?.postCount }}</span>
                <span class="stat-label">帖子</span>
              </div>
            </div>
          </div>
        </el-card>
        <el-card class="user-card" @click="goUserCenter(postInfo?.userId)">
          <div class="user-header">
            <el-avatar :src="postInfo?.userInfo?.avatar" :size="64" class="user-avatar"></el-avatar>
            <div class="user-name">{{ postInfo?.userInfo?.nickname }}</div>
          </div>
          <div class="user-stats">
            <div class="stat-item">
              <span class="stat-value">{{ postInfo?.userInfo?.postCount }}</span>
              <span class="stat-label">帖子</span>
            </div>
            <div class="stat-item">
              <span class="stat-value">{{ postInfo?.userInfo?.followCount }}</span>
              <span class="stat-label">关注</span>
            </div>
          </div>
          <div class="user-action">
            <el-button type="primary" @click="goUserCenter(postInfo?.userInfo.userId)" plain>查看主页</el-button>
          </div>
        </el-card>
      </div>
      <!-- 右侧帖子内容 -->
      <div class="post-content">
        <!-- 帖子详情 -->
        <el-card class="post-card">
          <div class="post-header">
            <h1 class="post-title">{{ postInfo?.title }}</h1>
            <div class="like-section" @click="likePost">
              <el-icon :size="28" class="like-icon">
                <IconLike v-if="postInfo?.isLiked" style="color: #ff4d4f;"/>
                <IconLike v-else class="image-hover"/>
              </el-icon>
              <span class="like-text">{{ postInfo?.isLiked ? '已点赞' : '点赞' }}</span>
            </div>
          </div>
          <div class="post-author">
            <el-avatar :src="postInfo?.userInfo?.avatar" :size="36"></el-avatar>
            <span class="author-name">{{ postInfo?.userInfo?.nickname }}</span>
            <span class="post-time">{{ formatTime(postInfo?.createTime) }}</span>
          </div>
          <div class="post-body">
            <p class="post-text">{{ postInfo?.content }}</p>
            <div class="post-images" v-if="postInfo?.files?.length">
              <div
                  v-for="(file, index) in postInfo?.files"
                  :key="index"
                  v-show="isImageFileType(file.fileType)"
                  class="image-container"
              >
                <el-image
                    :src="file.fileUrl"
                    :preview-src-list="postInfo.files.filter(f => isImageFileType(f.fileType)).map(f => f.fileUrl)"
                    :initial-index="index"
                    fit="cover"
                    class="post-image"
                    hide-on-click-modal
                ></el-image>
              </div>
            </div>
            <el-space>
              <el-tag v-for="tag in postInfo?.tags"> #{{ tag.tagName }}</el-tag>
            </el-space>
            <div class="flex-end">
              <el-button text type="primary" :icon="ChatDotRound" size="small" @click="createReplyDTO.parentId=0">回复
              </el-button>
            </div>
          </div>
        </el-card>
        <!-- 评论区域 -->
        <div class="comments-section">
          <el-card class="comments-header">
            <template #header>
              <div class="header-content">
                <span class="comments-title">评论</span>
                <span class="comments-count">({{ postInfo?.replies?.total || 0 }})</span>
              </div>
            </template>
            <el-skeleton :loading="loading" animated>
              <template #template>
                <div v-for="i in 3" :key="i" class="skeleton-comment">
                  <el-skeleton-item variant="image" class="skeleton-avatar"/>
                  <div class="skeleton-content">
                    <el-skeleton-item variant="h3" style="width: 30%"/>
                    <el-skeleton-item variant="text" style="width: 80%"/>
                    <el-skeleton-item variant="text" style="width: 60%"/>
                  </div>
                </div>
              </template>
              <template #default>
                <div v-if="postInfo?.replies?.list?.length === 0">
                  <el-empty description="暂无评论" :image-size="100"/>
                </div>
                <div
                    v-else
                    v-for="item in postInfo?.replies?.list"
                    :key="item.id"
                    class="comment-item"
                    :class="{ 'landlord-comment': postInfo?.userId === item?.userId }"
                >
                  <div v-if="postInfo?.userId == item?.userId" class="landlord-tag">
                    <span>楼主</span>
                  </div>
                  <div class="comment-header">
                    <el-avatar :src="item?.avatar" class="comment-avatar"></el-avatar>
                    <div class="comment-user">
                      <div class="user-name">{{ item?.nickname }}</div>
                      <div class="comment-time">{{ formatTime(item?.createTime) }}</div>
                    </div>
                  </div>
                  <div class="comment-body">
                    <p>{{ item?.content }}</p>
                    <div class="comment-images" v-if="item?.files?.length">
                      <el-row :gutter="10">
                        <el-col
                            :span="8"
                            v-for="(file, idx) in item?.files"
                            :key="idx"
                            v-show="isImageFileType(file.fileType)"
                        >
                          <el-image
                              :src="file.fileUrl"
                              fit="cover"
                              class="comment-image"
                              :preview-src-list="item.files.filter(f => isImageFileType(f.fileType)).map(f => f.fileUrl)"
                              :initial-index="idx"
                              hide-on-click-modal
                          ></el-image>
                        </el-col>
                      </el-row>
                    </div>
                  </div>
                  <div class="comment-actions">
                    <el-space>
                      <el-text v-if="!item.showRely" size="small" @click="getReplyList(item)">展开查看回复
                        <el-icon>
                          <ArrowUp/>
                        </el-icon>
                      </el-text>
                      <el-text v-else size="small" @click="item.showRely=false">收起回复
                        <el-icon>
                          <ArrowDown/>
                        </el-icon>
                      </el-text>
                      <el-button text type="primary" :icon="ChatDotRound" size="small"
                                 @click="createReplyDTO.parentId=item.replyId">回复
                      </el-button>
                    </el-space>
                  </div>
                  <div v-if="item.showRely" class="reply">
                    <div v-for="reply in item.replies">
                    <el-space>
                      <el-avatar :src="reply.avatar"></el-avatar>
                      <el-text>{{reply?.nickname}}</el-text>
                    </el-space>
                      <div>
                        回复：{{reply?.content}}
                      </div>
                    </div>
                  </div>
                </div>
              </template>
            </el-skeleton>
          </el-card>
          <!-- 发表评论区域 -->
          <div v-if="!isLogin" class="login-prompt">
            <el-button type="primary" @click="router.push('/login')">登录后发表评论</el-button>
          </div>
          <el-card v-else class="reply-form">
            <h3 class="form-title">{{ getReplyTarget }}</h3>
            <el-form>
              <el-form-item>
                <el-input
                    v-model="createReplyDTO.content"
                    type="textarea"
                    :rows="3"
                    placeholder="写下你的回复..."
                    maxlength="300"
                    show-word-limit
                ></el-input>
              </el-form-item>
              <el-form-item>
                <UploadButtonNoView @upload-file="upFile" url="post/reply"/>
                <div class="file-tips">支持上传图片（最多9张）</div>
              </el-form-item>
              <el-form-item>
                <el-button type="primary" @click="submitPostReply" class="submit-btn">提交回复</el-button>
              </el-form-item>
            </el-form>
          </el-card>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import {ref, reactive, onMounted, computed} from "vue";
import {Plus, Search, ChatDotRound, ArrowDown} from '@element-plus/icons-vue'
import {useRoute, useRouter} from "vue-router";
import {reqGetBardByPostId} from '@/api/social/bard'
import {useUserStore} from "@/stores/user";
import type {SocBardVO} from "@/api/social/bard/type";
import type {SocPostInfoVO, SocPostReplyDTO} from "@/api/social/posts/type";
import {
  reqGetPostInfoVO,
  reqCreatePostReply,
  reqLikePost,
  reqGetPostReplChildrenList,
  reqGetPostReplyPage
} from "@/api/social/posts";
import {isImageFileType} from "@/utils/file";
import UploadButtonNoView from "@/components/uploader/UploadButtonNoView.vue";
import type {UpFileDTO} from "@/components/uploader/UploadButtonNoView.vue";
import {storeToRefs} from "pinia";
import {ElMessage} from 'element-plus'

const route = useRoute()
const router = useRouter()
const userStore = useUserStore()
const {isLogin} = storeToRefs(userStore)
let bardInfo = ref<SocBardVO>()
let postInfo = ref<SocPostInfoVO>()
let postInfoQuery = reactive({
  postId: route.query.postId as string,
  pageNum: 1,
  pageSize: 7,
  parentId: 0
})
let replyQuery = reactive({
  parentId: null,
  pageNum: 1,
  pageSize: 7
})
let createReplyDTO = reactive<SocPostReplyDTO>({
  replyId: 0,
  postId: route.query.postId as string,
  parentId: 0,
  content: '',
  status: 0,
  files: []
})
let loading = ref(true)

let goUserCenter= (userId: string | number) => {
  router.push({
    name: 'user-center',
    params: {userId}
  })
}
const likePost = async () => {
  if (isLogin.value) {
    await reqLikePost({postId: postInfo.value?.postId as string})
    await getPostInfo()
  } else {
    ElMessage.warning("请先登录后再操作")
  }
}

const getBardInfo = async () => {
  const res = await reqGetBardByPostId(route.query.postId as string)
  bardInfo.value = res.data
}

const getPostInfo = async () => {
  let res = await reqGetPostInfoVO(postInfoQuery)
  postInfo.value = res.data
  loading.value = false
}

const upFile = (fileInfo: UpFileDTO) => {
  if (createReplyDTO.files.length < 9) {
    createReplyDTO.files.push({
      fileUrl: fileInfo.fileUrl,
      fileType: fileInfo.fileType,
    })
  } else {
    ElMessage.warning("最多只能上传9张图片")
  }
}
let getReplyList = async (item) => {
  item.showRely = true
  replyQuery.parentId = item.replyId
  let res = await reqGetPostReplyPage(replyQuery)
   item.replies = res.data.list
}
const submitPostReply = async () => {
  if (!createReplyDTO.content.trim()) {
    ElMessage.warning("请填写回复内容")
    return
  }
  await reqCreatePostReply(createReplyDTO)
  getPostInfo()
  resetReplyForm()
}

const resetReplyForm = () => {
  createReplyDTO.content = ''
  createReplyDTO.files = []
}

const formatTime = (timeStr: string) => {
  if (!timeStr) return ''
  const date = new Date(timeStr)
  return `${date.getFullYear()}-${(date.getMonth() + 1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')} ${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}`
}
let getReplyTarget = computed(() => {
  if (createReplyDTO.parentId === 0) {
    return '回复帖子'
  }
  return `回复${postInfo.value?.replies.list.find(item => item.replyId === createReplyDTO.parentId).nickname}的评论`
})
onMounted(() => {
  getBardInfo()
  getPostInfo()
})
</script>

<style scoped lang="scss">
.post-detail-container {
  max-width: 1400px;
  margin: 0 auto;
  padding: 20px;
  background-color: #f5f7fa;
  min-height: 100vh;
}

.breadcrumb-section {
  padding: 15px 0;
  margin-bottom: 20px;
  background-color: white;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);

  .el-breadcrumb {
    padding: 0 20px;
    font-size: 15px;
  }
}

.main-content {
  display: flex;
  gap: 20px;
  @media (max-width: 992px) {
    flex-direction: column;
  }
}

.sidebar {
  width: 280px;
  flex-shrink: 0;
  @media (max-width: 992px) {
    width: 100%;
  }
}

.post-content {
  flex: 1;
}

.bard-card {
  margin-bottom: 20px;
  border-radius: 12px;
  overflow: hidden;
  transition: transform 0.3s, box-shadow 0.3s;

  &:hover {
    transform: translateY(-5px);
    box-shadow: 0 10px 20px rgba(0, 0, 0, 0.1);
  }

  .bard-cover {
    height: 150px;

    .cover-image {
      width: 100%;
      height: 100%;
      border-radius: 8px 8px 0 0;
    }
  }

  .bard-info {
    padding: 15px;
    text-align: center;

    h3 {
      margin: 10px 0;
      color: #333;
      font-size: 18px;
    }

    .follow-btn {
      width: 100%;
      margin: 10px 0;
      height: 40px;
      border-radius: 20px;
      font-weight: bold;
    }

    .bard-stats {
      display: flex;
      justify-content: space-around;
      margin-top: 15px;

      .stat-item {
        display: flex;
        flex-direction: column;

        .stat-value {
          font-size: 18px;
          font-weight: bold;
          color: #1e88e5;
        }

        .stat-label {
          font-size: 13px;
          color: #666;
        }
      }
    }
  }
}
.reply{
  padding-left: 20px;
  background-color: rgba(84, 92, 100, 0.44);
}
.user-card {
  border-radius: 12px;
  cursor: pointer;
  transition: transform 0.3s, box-shadow 0.3s;

  &:hover {
    transform: translateY(-5px);
    box-shadow: 0 10px 20px rgba(0, 0, 0, 0.1);
  }

  .user-header {
    display: flex;
    flex-direction: column;
    align-items: center;
    padding: 15px 0;

    .user-avatar {
      border: 2px solid #1e88e5;
      margin-bottom: 10px;
    }

    .user-name {
      font-weight: bold;
      font-size: 16px;
      color: #333;
    }
  }

  .user-stats {
    display: flex;
    justify-content: space-around;
    margin: 15px 0;
    padding: 10px 0;
    border-top: 1px solid #eee;
    border-bottom: 1px solid #eee;

    .stat-item {
      display: flex;
      flex-direction: column;
      align-items: center;

      .stat-value {
        font-size: 16px;
        font-weight: bold;
        color: #ff9800;
      }

      .stat-label {
        font-size: 13px;
        color: #666;
      }
    }
  }

  .user-action {
    display: flex;
    justify-content: center;

    .el-button {
      border-radius: 20px;
      padding: 8px 25px;
    }
  }
}

.post-card {
  border-radius: 12px;
  margin-bottom: 20px;
  transition: box-shadow 0.3s;

  &:hover {
    box-shadow: 0 6px 16px rgba(0, 0, 0, 0.12);
  }

  .post-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 15px;
    padding-bottom: 15px;
    border-bottom: 1px solid #f0f0f0;

    .post-title {
      margin: 0;
      font-size: 24px;
      color: #1a1a1a;
      flex: 1;
    }

    .like-section {
      display: flex;
      flex-direction: column;
      align-items: center;
      cursor: pointer;
      user-select: none;
      transition: all 0.2s;

      &:hover {
        transform: scale(1.05);

        .like-icon {
          color: #ff4d4f;
        }
      }

      .like-icon {
        transition: color 0.2s;
      }

      .like-text {
        font-size: 12px;
        color: #666;
        margin-top: 5px;
      }
    }
  }

  .post-author {
    display: flex;
    align-items: center;
    margin-bottom: 20px;

    .el-avatar {
      margin-right: 10px;
    }

    .author-name {
      font-weight: bold;
      margin-right: 15px;
      color: #1e88e5;
    }

    .post-time {
      color: #999;
      font-size: 13px;
    }
  }

  .post-body {
    .post-text {
      font-size: 16px;
      line-height: 1.8;
      color: #333;
      margin-bottom: 20px;
    }

    .post-images {
      display: grid;
      grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
      gap: 15px;

      .image-container {
        border-radius: 8px;
        overflow: hidden;
        height: 200px;

        .post-image {
          width: 100%;
          height: 100%;
          object-fit: cover;
          transition: transform 0.3s;
          cursor: pointer;

          &:hover {
            transform: scale(1.03);
          }
        }
      }
    }
  }
}

.comments-section {
  .comments-header {
    border-radius: 12px;
    margin-bottom: 20px;

    :deep(.el-card__header) {
      background: linear-gradient(135deg, #e3f2fd, #bbdefb);
      border-radius: 12px 12px 0 0;
    }

    .header-content {
      display: flex;
      align-items: center;

      .comments-title {
        font-size: 18px;
        font-weight: bold;
        color: #0d47a1;
      }

      .comments-count {
        margin-left: 8px;
        color: #1e88e5;
        font-weight: bold;
      }
    }
  }

  .skeleton-comment {
    display: flex;
    padding: 15px;
    border-bottom: 1px solid #eee;

    .skeleton-avatar {
      width: 40px;
      height: 40px;
      border-radius: 50%;
      margin-right: 15px;
    }

    .skeleton-content {
      flex: 1;
    }
  }

  .comment-item {
    padding: 20px;
    margin-bottom: 15px;
    background-color: white;
    border-radius: 8px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
    transition: all 0.3s;
    position: relative;

    &:hover {
      box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
      transform: translateY(-2px);
    }

    .landlord-tag {
      position: absolute;
      top: 0;
      left: 0;
      background-color: #ff9800;
      color: white;
      font-size: 12px;
      padding: 3px 10px;
      border-radius: 0 0 12px 0;
      font-weight: bold;
    }

    .comment-header {
      display: flex;
      align-items: center;
      margin-bottom: 15px;

      .comment-avatar {
        margin-right: 12px;
      }

      .comment-user {
        .user-name {
          font-weight: bold;
          color: #333;
        }

        .comment-time {
          font-size: 12px;
          color: #999;
        }
      }
    }

    .comment-body {
      p {
        margin: 0 0 15px 0;
        line-height: 1.6;
        color: #333;
      }

      .comment-images {
        margin-top: 10px;

        .comment-image {
          width: 100%;
          height: 100px;
          border-radius: 6px;
          cursor: pointer;
          transition: transform 0.3s;

          &:hover {
            transform: scale(1.03);
          }
        }
      }
    }

    .comment-actions {
      display: flex;
      justify-content: flex-end;
      margin-top: 10px;
    }
  }

  .landlord-comment {
    border-left: 3px solid #ff9800;
  }

  .login-prompt {
    display: flex;
    justify-content: center;
    padding: 30px;
    background-color: white;
    border-radius: 12px;
    margin-bottom: 20px;

    .el-button {
      border-radius: 20px;
      padding: 12px 30px;
      font-weight: bold;
    }
  }

  .reply-form {
    border-radius: 12px;

    .form-title {
      margin-top: 0;
      font-size: 18px;
      color: #333;
      padding-bottom: 15px;
      border-bottom: 1px solid #eee;
    }

    .file-tips {
      font-size: 12px;
      color: #999;
      margin-top: 5px;
    }

    .submit-btn {
      border-radius: 20px;
      padding: 10px 30px;
      font-weight: bold;
      float: right;
      width: 100%;
    }
  }
}
</style>
